package com.offcn.question.service.impl;


import com.alibaba.nacos.client.utils.StringUtils;
import com.offcn.question.entity.TypeEntity;
import com.offcn.question.service.TypeService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.common.utils.PageUtils;
import com.offcn.common.utils.Query;

import com.offcn.question.dao.QuestionDao;
import com.offcn.question.entity.QuestionEntity;
import com.offcn.question.service.QuestionService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao, QuestionEntity> implements QuestionService {

    @Resource
    private TypeService typeService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<QuestionEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("TYPE",key).or().eq("title",key).or().eq("id",key);
        }
        IPage<QuestionEntity> page = this.page(
                new Query<QuestionEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public Map importExcel(MultipartFile file) {
        //存储导入返回信息
        Map result =new HashMap();
        //获取文件名
        String filename = file.getOriginalFilename();
        //如果文件后缀不是xls或者xlsx无法导入
        if (!filename.matches("^.+\\.(?i)(xls)$") && !filename.matches("^.+\\.(?i)(xlsx)$")){
            result.put("result",false);
            result.put("msg","文件扩展名不正确，导入失败");
            result.put("num",0);
        }
        //存储表条数信息
        List<QuestionEntity>list = new ArrayList<>();
        try {
            //创建流对象
            InputStream inputStream = file.getInputStream();
            //获取工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //获取表
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            //获取总行数
            int rows = sheetAt.getPhysicalNumberOfRows();
            //遍历总行数
            for (int i = 1; i < rows; i++) {
                //创建存储对象
                QuestionEntity questionEntity = new QuestionEntity();
                //获取每一行
                XSSFRow row = sheetAt.getRow(i);
                //读取数据进行存储封装进对象
                questionEntity.setTitle(row.getCell(0).getStringCellValue());
                questionEntity.setAnswer(row.getCell(1).getStringCellValue());
                questionEntity.setLevel((int) row.getCell(2).getNumericCellValue());
                questionEntity.setDisplayOrder((int) row.getCell(3).getNumericCellValue());
                questionEntity.setSubTitle(row.getCell(4).getStringCellValue());
                questionEntity.setType((long) row.getCell(5).getNumericCellValue());
                questionEntity.setEnable((int) row.getCell(6).getNumericCellValue());
                //保存到存储条数集合
                list.add(questionEntity);
                //添加到数据库
                this.save(questionEntity);
                //封装返回信息
                result.put("result",true);
                result.put("msg","导入成功");
                result.put("num",list.size());
            }

        } catch (IOException e) {
            e.printStackTrace();
            result.put("result",false);
            result.put("msg","导入失败"+e.getMessage());
            result.put("num",0);
        }
        return result;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        //创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建表
        HSSFSheet sheet = workbook.createSheet();
        //创建第一行  设置导读信息
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("题目标题");
        row.createCell(1).setCellValue("题目解答");
        row.createCell(2).setCellValue("题目难度等级");
        row.createCell(3).setCellValue("排序");
        row.createCell(4).setCellValue("副标题");
        row.createCell(5).setCellValue("题目类型");
        row.createCell(6).setCellValue("是否显示");
        //获取要下载的数据
        List<QuestionEntity> list = this.list();
        //遍历下载
        for (int i = 0; i < list.size(); i++) {
            HSSFRow sheetRow = sheet.createRow(i+1);
            sheetRow.createCell(0).setCellValue(list.get(i).getTitle());
            sheetRow.createCell(1).setCellValue(list.get(i).getAnswer());
            sheetRow.createCell(2).setCellValue(list.get(i).getLevel());
            sheetRow.createCell(3).setCellValue(list.get(i).getDisplayOrder());
            sheetRow.createCell(4).setCellValue(list.get(i).getSubTitle());
            sheetRow.createCell(5).setCellValue(list.get(i).getType());
            sheetRow.createCell(6).setCellValue(list.get(i).getEnable());
        }
        //如果有读取到数据
        if(workbook!=null){
            //拼接文件名
            String filename = "uxue_"+ UUID.randomUUID()+".xlsx";
            //设置下载响应头
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            //设置编码格式
            response.setContentType("application/octet-stream;charset=GB2312");
            response.setCharacterEncoding("GB2312");
            try {
                //下载
                ServletOutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                response.getWriter().print("error");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Map<String, Object>> countTypeQuestion() {
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        //查询QuestionEntity得到题目总数和题目类型ID
        queryWrapper.select("TYPE,COUNT(TYPE) AS num").groupBy("TYPE");
        List<Map<String, Object>> mapList = baseMapper.selectMaps(queryWrapper);
        //遍历集合
        for (Map<String, Object> map : mapList){
            //根据题目类型ID查询
            long typeId = (long)map.get("TYPE");
            TypeEntity typeEntity = typeService.getById(typeId);
            //把题目类型名进行重新封装
            map.put("name",typeEntity.getType());
        }
        return mapList;
    }

}